from flask import Blueprint, request, jsonify, session
from models.user import User
from models.card import Card
from models.transaction import Transaction
from utils.database import db

customer_bp = Blueprint('customer', __name__)

@customer_bp.route('/account', methods=['GET'])
def get_account_info():
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '未登录'}), 401
    
    user = User.query.get(user_id)
    cards = Card.query.filter_by(customer_id=user_id).all()
    
    return jsonify({
        'success': True,
        'user': {
            'name': user.customer_name,
            'pid': user.pid,
            'telephone': user.telephone,
            'address': user.address
        },
        'cards': [{
            'card_id': c.card_id,
            'balance': float(c.balance),
            'open_date': c.open_date.strftime('%Y-%m-%d'),
            'is_report_loss': c.is_report_loss,
            'saving_type': c.deposit_type.saving_name
        } for c in cards]
    })

@customer_bp.route('/deposit', methods=['POST'])
def deposit():
    data = request.get_json()
    card_id = data.get('card_id')
    amount = data.get('amount')
    
    # 验证数据...
    
    card = Card.query.get(card_id)
    if not card:
        return jsonify({'success': False, 'message': '银行卡不存在'}), 404
    
    # 更新余额
    card.balance += amount
    
    # 记录交易
    new_transaction = Transaction(
        trade_type='deposit',
        trade_money=amount,
        card_id=card_id,
        remark='存款'
    )
    
    db.session.add(new_transaction)
    db.session.commit()
    
    return jsonify({'success': True, 'message': '存款成功', 'balance': float(card.balance)})

# 取款、转账、修改密码等其他路由...
# 银行项目/controllers/customer.py
from flask import Blueprint, request, jsonify, session
from models.user import User
from models.card import Card
from models.transaction import Transaction
from utils.database import db
import logging

customer_bp = Blueprint('customer', __name__)
logger = logging.getLogger(__name__)

@customer_bp.route('/account', methods=['GET'])
def get_account_info():
    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'success': False, 'message': '未登录'}), 401

        user = User.query.get(user_id)
        cards = Card.query.filter_by(customer_id=user_id).all()

        return jsonify({
            'success': True,
            'user': {
                'name': user.customer_name,
                'pid': user.pid,
                'telephone': user.telephone,
                'address': user.address
            },
            'cards': [{
                'card_id': c.card_id,
                'balance': float(c.balance),
                'open_date': c.open_date.strftime('%Y-%m-%d'),
                'is_report_loss': c.is_report_loss,
                'saving_type': c.deposit_type.saving_name if c.deposit_type else '未知'
            } for c in cards]
        })
    except Exception as e:
        logger.error(f"获取账户信息失败: {e}")
        return jsonify({'success': False, 'message': '获取账户信息失败'}), 500

@customer_bp.route('/deposit', methods=['POST'])
def deposit():
    try:
        data = request.get_json()
        card_id = data.get('card_id')
        amount = data.get('amount')

        # 验证数据...
        if not card_id or not amount:
            return jsonify({'success': False, 'message': '缺少必要参数'}), 400

        card = Card.query.get(card_id)
        if not card:
            return jsonify({'success': False, 'message': '银行卡不存在'}), 404

        # 更新余额
        card.balance += amount

        # 记录交易
        new_transaction = Transaction(
            trade_type='deposit',
            trade_money=amount,
            card_id=card_id,
            remark='存款'
        )

        db.session.add(new_transaction)
        db.session.commit()

        return jsonify({'success': True, 'message': '存款成功', 'balance': float(card.balance)})
    except Exception as e:
        logger.error(f"存款失败: {e}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '存款失败'}), 500

@customer_bp.route('/withdraw', methods=['POST'])
def withdraw():
    try:
        data = request.get_json()
        card_id = data.get('card_id')
        amount = data.get('amount')

        # 验证数据...
        if not card_id or not amount:
            return jsonify({'success': False, 'message': '缺少必要参数'}), 400

        card = Card.query.get(card_id)
        if not card:
            return jsonify({'success': False, 'message': '银行卡不存在'}), 404

        if card.balance < amount:
            return jsonify({'success': False, 'message': '余额不足'}), 400

        # 更新余额
        card.balance -= amount

        # 记录交易
        new_transaction = Transaction(
            trade_type='withdraw',
            trade_money=amount,
            card_id=card_id,
            remark='取款'
        )

        db.session.add(new_transaction)
        db.session.commit()

        return jsonify({'success': True, 'message': '取款成功', 'balance': float(card.balance)})
    except Exception as e:
        logger.error(f"取款失败: {e}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '取款失败'}), 500

@customer_bp.route('/transfer', methods=['POST'])
def transfer():
    try:
        data = request.get_json()
        from_card_id = data.get('from_card_id')
        to_card_id = data.get('to_card_id')
        amount = data.get('amount')

        # 验证数据...
        if not from_card_id or not to_card_id or not amount:
            return jsonify({'success': False, 'message': '缺少必要参数'}), 400

        from_card = Card.query.get(from_card_id)
        to_card = Card.query.get(to_card_id)

        if not from_card or not to_card:
            return jsonify({'success': False, 'message': '银行卡不存在'}), 404

        if from_card.balance < amount:
            return jsonify({'success': False, 'message': '余额不足'}), 400

        # 更新余额
        from_card.balance -= amount
        to_card.balance += amount

        # 记录交易
        new_transaction_from = Transaction(
            trade_type='transfer_out',
            trade_money=amount,
            card_id=from_card_id,
            remark=f'转账到 {to_card_id}'
        )

        new_transaction_to = Transaction(
            trade_type='transfer_in',
            trade_money=amount,
            card_id=to_card_id,
            remark=f'从 {from_card_id} 转入'
        )

        db.session.add(new_transaction_from)
        db.session.add(new_transaction_to)
        db.session.commit()

        return jsonify({'success': True, 'message': '转账成功', 'balance': float(from_card.balance)})
    except Exception as e:
        logger.error(f"转账失败: {e}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '转账失败'}), 500